package link.cocoon.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import link.cocoon.common.base.BaseService;
import link.cocoon.blog.entity.Article;
import link.cocoon.blog.mapper.ArticleMapper;
import link.cocoon.blog.service.ArticleService;
import link.cocoon.common.util.MarkdownUtil;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Cocoon
 * @since 2020-03-31
 */
@Service
@CacheConfig( cacheNames = "article" )
public class ArticleServiceImpl extends BaseService<ArticleMapper, Article> implements ArticleService {


  @Override
  public int create(Article entity) {
    summaryHandle(entity);
    return super.create(entity);
  }

  @Override
  public int update(Article entity) {
    summaryHandle(entity);
    return super.update(entity);
  }

  @Override
  public long countByCategoryId(Long categoryId){
    return getBaseMapper().selectCount(new QueryWrapper<Article>().lambda().eq(Article::getCategoryId,categoryId));
  }

  @Cacheable
  @Override
  public <E extends IPage<Article>> E page(E page, Wrapper<Article> wrapper) {
    return super.page(page, wrapper);
  }

  private void summaryHandle(Article article){
    String md = article.getContent();
    String summary = MarkdownUtil.toText(md);
    article.setSummary(summary.substring(0,400));
  }
}
